package fragments.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class TitleFragment extends ListFragment {
	
	ArrayList<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
	ListView titleListView = null;
	OnTitleSelectedListener titleSelectedListener;
	
	// OnTitleSelectedListener 接口在TitleFragment中声明， 为了实现世界容器Activity必须实现这个接口
	public interface OnTitleSelectedListener {
		public void onTitleSelected(int position);
	}
	
	/**
	 * 为了确保宿主Activity实现OnTitleSelectedListener借口，可以在Title Fragment的 onAttach()方法
	 * (当添加fragment到activity时由系统调用onAttach())中将作为参数传入onAttach()的Activity做类型转换来
	 * 实例化一个OnTitleSelectedListener实例. 如果activity没有实现接口, fragment会抛出 ClassCastException 
	 * 异常. 
	 */

     @Override
     public void onAttach(Activity activity) {
         super.onAttach(activity);
              
         try {
        	 titleSelectedListener = (OnTitleSelectedListener) activity;
         } catch (ClassCastException e) {
             throw new ClassCastException(activity.toString() + " must implement OnTitleSelectedListener");
         }
     }

	@Override
     public void onListItemClick(ListView l, View v, int position, long id) {
		// Append the clicked item's row ID with the content provider Uri 
        // Uri uri = ContentUris.withAppendedId(Columns.CONTENT_URI, id);
		// Send the event and Uri to the host activity
		titleSelectedListener.onTitleSelected(position);
     }

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
	    //创建数据
        for (int i = 0; i < 10; i++) {
	       	 Map<String, Object> item = new HashMap<String, Object>();
	       	 item.put("Author", R.drawable.ic_launcher);
	       	 item.put("AuthorName", "Author :" + i);
	       	 item.put("Title", "Title" + i);
	       	 
	       	 dataList.add(item);
        }
        
        //Adapter是 View 与 data之间的桥梁
        //dataList 放入 title_fragment 当中, String[]包含data每个字段, int[] 指定String[] 中字段被显示在那个View中  
        SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), dataList, R.layout.title_fragment, 
       		 new String[] {"Author","AuthorName","Title"}, 
       		 new int[] {R.id.imageViewAuthor, R.id.textViewAuthorName, R.id.textViewTitle});
        
        this.setListAdapter(simpleAdapter);
        //设置选择模式 为单行
        this.getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	}
}
